<?php

//cookie encrypt key
$secKey = 'ffb6991624af0df4fb8edfefc2b0b4c2';

/**
 *
 * get user infomation from cookie
 *
 * @global array $_COOKIE
 * @global string $secKey
 * @return boolean or array
 */
function getUserFromCookie() {
	global $_COOKIE;
	global $secKey;
	if(!isset($_COOKIE[CP_AUTH_TOKEN]))
		return false;
	$d = base64_decode($_COOKIE[CP_AUTH_TOKEN]);
	list($a, $c) = explode(";", $d, 2);
	if(md5("$a;$secKey") == $c) {
		list($username, $id, $time) = explode(',', $a);
		return array('username'=>$username, 'userid'=>$id, 'time'=>$time);
	}
	//cookie not valid
	else {
		setcookie(CP_AUTH_TOKEN, '', time()-3600, '/', COOKIE_DOMAIN, 0);
		//setcookie(CP_AUTH_TOKEN, '', time()-3600, '/' );
		return false;
	}
	return false;
}

/**
 *
 * set user cookie, when user login
 *
 * @global array $_COOKIE
 * @global string $secKey
 * @param int $userId
 * @param string $userName
 * @param boolean $rememberUser
 */
function setUserToCookie( $userId, $userName, $rememberUser=false ) {
	global $_COOKIE;
	global $secKey;
	$time = time();

	$a = "$userName,$userId, $time";
	$c = md5("$a;$secKey");
	$d = base64_encode("$a;$c");
	if($rememberUser) {
		$time = $time + 604800*4;
	}else {
		$time = null;
	}
	setcookie(CP_AUTH_TOKEN,$d, $time , '/', COOKIE_DOMAIN);
	//setcookie(CP_AUTH_TOKEN,$d, $time , '/' );
}

/**
 * invalid cookie to logout
 */
function logoutUser() 
{
	setcookie(CP_AUTH_TOKEN, '', time()-3600, '/', COOKIE_DOMAIN);
	unset( $_COOKIE[CP_AUTH_TOKEN] );
	//setcookie(CP_AUTH_TOKEN, '', time()-3600, '/' );
}
?>
